﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Emerson.Storage.Service.Interface;
using Emerson.Storage.Entities;
using System.Web.Services;
using System.Web.Script.Services;
using System.ComponentModel;
using System.Threading;

namespace WorkstationDashboard
{
    public partial class ContentDevice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BuildTreeView();
                deviceId.Value = Request.Params["id"];
                Utility.SelectNode(Master.WorkstationTreeView, NodeType.Device, int.Parse(deviceId.Value));
                SetDeviceInfo();
            }
        }

        private void SetDeviceInfo()
        {
            int id = int.Parse(deviceId.Value);
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();

            Battery bat = wsService.GetBattery(id);

            batteryName.Text = bat.BatteryType + bat.BatteryId.ToString();
            batteryType.Text = bat.BatteryType;
            batteryVersion.Text = bat.FirewareVersion;
            powerLevel.Text = bat.PercentRemaining.ToString();
            isConnected.Text = bat.IsConnected.ToString();
            lastConnectedTime.Text = bat.LogTime.ToString();
            temperature.Text = bat.Temperature.ToString();
        }

        private void BuildTreeView()
        {
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();

            WorkstationRoot wkRoot = wsService.GetWorkstationRoot();
            TreeNode treeRoot = Utility.BuildTreeFromWorkstationRoot(wkRoot);
            Master.WorkstationTreeView.Nodes.Clear();
            Master.WorkstationTreeView.Nodes.Add(treeRoot);
        }

        [WebMethod]
        [ScriptMethod]
        public static void RemoveDevice(string idString)
        {
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();
            int deviceId = int.Parse(idString);
            wsService.DeleteBattery(deviceId);
        }
    }
}
